<?php
namespace app\common\service;
use app\api\controller\v1\Member;
use app\common\model\OrderQuery;
use think\Db;
use \app\common\model\User as UserMode;
use \app\common\model\Area as AreaMode;
use \app\common\model\LitestoreShop as LitestoreShopMode;
use app\common\model\UserIntegral;
use Endroid\QrCode\QrCode;
use think\Exception;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/7
 * Time: 11:56
 */
class User extends Base {
    public function __construct()
    {
        parent::__construct();
        $UserMode =  new UserMode();
        $this->model = $UserMode;
        $this->ShopMode=new  LitestoreShopMode();
        $this->AreaMode=new AreaMode();
    }
    public function getUerinfoByUid($map){
       return $this->model->find($map);
    }
    /**
     * 我的邀请列表
     */
    public  function myCodeListService($live,$user_id,$limit=10,$page=1)
    {
        $arr = [];
        if ($live == 1){
            $arr = $this->model->where('parent_id',$user_id)->field('id,username,createtime')
                ->page($page)
                ->limit($limit)
                ->select();

        }elseif ($live == 2){
            $uids = $this->model->where('parent_id',$user_id)->column('id');
            if(!$uids) return $arr;
            $arr = $this->model
                ->where('parent_id','in',$uids)
                ->field('id,username,createtime')
                ->order('id desc')
                ->page($page)
                ->limit($limit)
                ->select();
        }
        return $arr ;
    }

    /**
     * 修改个人资料
     */
    public function upMyInfo($username,$uid){
        if(!empty($username)){
            $map['nickname'] = $username;
        }
        if(empty($map)){
          return false;
        }
        return $this->model->save($map,['id'=>$uid]);
    }

    /**
     * 生成二维码
     */
    public function createcode($code){
        $url = url('/index/index/index',array('code'=>$code),true,true);

        $file=$imagePath='codes/usercode/ercode_'.$code.'.png';
        if(file_exists($file)){
            return  '/'.$file;
        }else{
            $qrCode =  new QrCode();//创建生成二维码对象
            $qrCode->setText($url)
                ->setSize(150)
                ->setPadding(10)
                ->setErrorCorrection('high')
                ->setForegroundColor(array('r' => 0, 'g' => 0, 'b' => 0, 'a' => 0))
                ->setBackgroundColor(array('r' =>225, 'g' => 225, 'b' => 225, 'a' => 0))
                ->setImageType(\Endroid\QrCode\QrCode::IMAGE_TYPE_PNG)
                ->save($file);
        }
        return '/'.$file;
    }


    /**
     * 注册查询上一级，一致到有个权为止，把个权id更新到本user_id对应的个权id
     * @param $user_id          当前传入user_id
     * @param int $parent_id    上一级parent_id,默认0,调用不用传这个参数-是递归比传
     * @return bool             返回真或者假处理结果
     */
    public function getAgentId($user_id,$parent_id=0){
        try{
            if(!empty($parent_id)){
                $where['id']=array('eq',$parent_id);
            }else{
                $where['id']=array('eq',$user_id);
            }
            $parent_user=$this->model
                ->where($where)
                ->field('id,parent_id,agent_id,is_agent')
                ->find();
            if(!empty($parent_user['is_agent'])&&!empty($parent_id)){
                $whereUpdate['id']=array('eq',$user_id);
                $data['agent_id']=$parent_user['id'];
                $this->model->save($data,$whereUpdate);
                return true;
            }
            if(!empty($parent_user['parent_id'])){
                $this->getAgentId($user_id,$parent_user['parent_id']);
            }
        }catch (\Exception $e){
            return false;
        }
        return true;
    }

    /**
     * 个权审核操作调用
     * @param $user_id  当前审核用户id
     * @return bool     返回执行金额
     */
    public function VerifySetAgentId($user_id,&$next_id=0){
        try{

            $agent_id=$this->getAagetUserId($user_id);
            $where['id']=array('gt',$user_id);
            $where['agent_id']=array('eq',$agent_id);
            $data['agent_id']=$user_id;
            $AgentArray=$this->model->where($where)->select();

            foreach ($AgentArray as $value) {
                $whereNew['id'] = $value['id'];
                db('user')->where($whereNew)->update($data);
            }


        }catch (\Exception $e){
            return false;
        }
        return true;
    }

    /**
     * 查询上一级个权用户id
     * @param $user_id      调用必须传递当前用户id
     * @param int $agent_id 自己函数内部赋值使用
     * @return int|mixed    返回数字
     */
    public function getAagetUserId($user_id,&$agent_id=0){
        try{
            $parent_user=$this->model
                ->where(['id'=>$user_id])
                ->field('id,parent_id,is_agent')->find();
            if(!empty($parent_user['parent_id'])){
                $agent=$this->model
                    ->where(['id'=>$parent_user['parent_id']])
                    ->field('id,parent_id,is_agent')
                    ->find();
                $agent_id=$agent['id'];
                if(!empty($agent['is_agent'])){
                    return $agent_id;
                }else{
                    $this->getAagetUserId($parent_user['parent_id'],$agent_id);
                }

            }
        }catch (\Exception $e){
            return 0;
        }
        return $agent_id;
    }

    /**
     * 必须是（上级个权,上上级个权）
     * 传入商家user_id就是商家二级查询（上级个权,上上级个权）
     * 如果是消费这user_id就是消费者二级（上级个权,上上级个权）
     * @param $user_id      用户id
     * @param array $array_list 函数自己使用变量无需传
     * @return array    返回（上级个权,上上级个权）数组
     */
    public function getShopAgentList($user_id,&$array_list=array()){
        try{
            $parent_user=$this->model
                ->where(['id'=>$user_id])
                ->field('id,agent_id,is_agent')->find();
            if(!empty($parent_user['agent_id'])){
                $agent=$this->model
                    ->where(['id'=>$parent_user['agent_id']])
                    ->field('id,agent_id,is_agent,parent_id,consume_res,contribute_res,money,residual,score,integer_res')
                    ->find();
                $array_list[]=$agent;
                $level=count($array_list);
                $agent->level=$level;
                if(count($array_list)<2){
                    $this->getShopAgentList($parent_user['agent_id'],$array_list);
                }else{
                    return $array_list;
                }
            }
        }catch (\Exception $e){
            return [];
        }
        return $array_list;
    }


    /**
     * 当前user_id就是二级查询（上级,上上级）
     * @param $user_id          用户id
     * @param array $array_list 函数自己使用变量无需传
     * @return array            返回（上级,上上级）数组
     */
    public function getParentListUser($user_id,&$array_list=array()){
        try{
            $parent_user=$this->model
                ->where(['id'=>$user_id])
                ->field('id,parent_id,agent_id,is_agent')->find();

            if(!empty($parent_user['parent_id'])){
                $agent=$this->model
                    ->where(['id'=>$parent_user['parent_id']])
                    ->field('id,parent_id,agent_id,is_agent,parent_id,consume_res,contribute_res,money,residual,score,integer_res')
                    ->find();
                $array_list[]=$agent;
                if(count($array_list)<2){
                    $this->getParentListUser($agent->id,$array_list);
                }else{

                    return $array_list;
                }
            }
        }catch (\Exception $e){
            return [];
        }
        return $array_list;
    }

    /**
     * 获取商家
     * @param $user_id  商家用户id
     * @return array    返回结果集
     */
    public function getLocalHostAgent($user_id){
        try{
            $where['id']=array('eq',$user_id);
//            $where['is_agent']=array('eq',1);
            $data=$this->model
                ->where($where)
                ->field('id,parent_id,consume_res,contribute_res,money,residual,score,integer_res')
                ->find();


        }catch (\Exception $e){
            $data=[];
        }
        return $data;
    }


    /**
     * 必须是粉丝直属上级商家(判断是否为商家)
     * 传入支付用户user_id
     * @param $user_id      支付用户id
     * @param array $array_list 函数自己使用变量无需传
     * @return array    返回（粉丝直属上级商家）数组
     */
    public function getParentShopAgent($user_id){
        $array_list=array();
        try{

            //查询用户信息用于将要----查询直属上一级数据
            $parent_user=$this->model
                ->where(['id'=>$user_id])
                ->field('id,agent_id,is_shop,is_agent,parent_id')
                ->find();
            if(!empty($parent_user->parent_id)){

                //查询上一级数据
                $shopAgent=$this->model
                    ->where(['id'=>$parent_user->parent_id])
                    ->field('id,agent_id,is_shop,is_agent,parent_id,consume_res,contribute_res,money,residual,score,integer_res')
                    ->find();

                if($shopAgent->is_shop>0){
                    //判断直属上级是否为个权+商家
                    $array_list=$shopAgent;

                }

            }
        }catch (\Exception $e){
            return [];
        }
        return $array_list;
    }

    /**
     * 服务商代理（大区、省代理、市代理、区代理)
     * @param $shop_id  商家id
     * @return array    返回数据集
     */
    public function getServiceProxy($shop_id){

        try{
            $data=array();

            //获取商铺所在省分id,所在市id,所在区id
            $ShopList=$this->ShopMode
                ->where(['id'=>$shop_id])
                ->field('area,city,province')
                ->find();

            //通过商铺省份id获取大区id
            $regione=$this->AreaMode
                ->where(['id'=>$ShopList['province']])
                ->column('regione_id');

            $ShopList['regione']=$regione[0];

            //获取地区代理
            if(!empty($ShopList['area'])){
                $data=$this->getSelectRegion(3,0,0,$ShopList['area'],0);
            }

            //获取市地域代理
            if(!empty($ShopList['city'])){
                $City=$this->getSelectRegion(2,0,$ShopList['city'],0,0);
                $data=array_merge($data,$City);
            }

            //获取省地域代理
            if(!empty($ShopList['province'])){
                $Province=$this->getSelectRegion(1,$ShopList['province'],0,0,0);
                $data=array_merge($data,$Province);
            }

            //获取大区地域代理
            if(!empty($ShopList['regione'])){
                $Regione=$this->getSelectRegion(5,0,0,0,$ShopList['regione']);
                $data=array_merge($data,$Regione);
            }

        }catch (\Exception $e){
            return [];
        }
        return $data;
    }

    public function getIsParentIdShop($user_id,$shop_user_id){
       try{
           //获取支付用户信息
           $status=true;
           $userFind=\app\common\model\User::get($user_id);
           if(!empty($userFind->parent_id)){
               if($userFind->parent_id==$shop_user_id){
                   $parentfind=\app\common\model\User::get($shop_user_id);
                   if($parentfind->is_shop>0){
                       $status=false;
                   }
               }
           }
       }catch (Exception $e){
       }
       return $status;

    }

    /**
     * 各代理id只需传一个,代理类型参数必填
     * @param $SericeId     代理类型：1省代理、2市代理、3区代理、5大区代理
     * @param int $province 省代理id
     * @param int $city     市代理id
     * @param int $area     地区id
     * @param int $regione  大区id
     * @return array        返回处理结果数据集
     */
    public function getSelectRegion($SericeId,$province=0,$city=0,$area=0,$regione=0){
        try{
            $where['server_type']=array('eq',$SericeId);
            if(!empty($province)) $where['province']=array('eq',$province);
            if(!empty($city)) $where['city']=array('eq',$city);
            if(!empty($area)) $where['area']=array('eq',$area);
            if(!empty($regione)) $where['regione']=array('eq',$regione);

            $data=$this->model
                ->where($where)
                ->field('id,parent_id,consume_res,contribute_res,money,residual,score,integer_res')
                ->select();
        }catch (\Exception $e){
            return [];
        }
        return $data;
    }

    /**
     * 消费返积插入积分日志表中
     * @param $data
     * @return bool
     */
    public function SetIntegralInsert($data){
        try{
            Db::name('user_integral')->insert($data);
            $where['id']=array('eq',$data['user_id']);
            Db::name('user')->where($where)->setInc('integral',$data['integral']);
//            $UserIntegral=new UserIntegral();
//            $UserIntegral->allowField(true) ->saveAll($data);
        }catch (\Exception $e){
            return false;
        }
        return true;
    }

    /**
     * 客户端首次注册 和下载 送积分  并 他上级赚积分
     */
    public function IntegrallnsInfo($uid,$scan_score,$recommended_score,$down_integral){
        Db::startTrans();
        try{
            //是否首次注册
            $where['id']=$uid;
            $info = Db::name('user')->where($where)->find();
            if($info['is_first']==0){
                $map['id'] = $info['parent_id'];
                $data = [
                    'user_id'=>$info['parent_id'],
                    'integral'=>$recommended_score,
                    'type'=>3,
                    'remark'=>'推荐积分',
                    'createtime'=>time(),
                ];
                $res = $this->SetIntegralInsert($data);
                if($res){
                    $resgiter = [
                        'user_id'=>$uid,
                        'integral'=>$scan_score,
                        'type'=>1,
                        'remark'=>'推荐注册',
                        'createtime'=>time(),
                    ];
                    $resgiter_result = $this->SetIntegralInsert($resgiter);
                    $downlod = [
                        'user_id'=>$uid,
                        'integral'=>$down_integral,
                        'type'=>4,
                        'remark'=>'首次下载',
                        'createtime'=>time(),
                    ];
                    $downlod_result = $this->SetIntegralInsert($downlod);
                    if($resgiter_result&&$downlod_result){
                        Db::name('user')->where($where)->update(['is_first'=>1]);
                        Db::commit();
                        return true;
                    }else{
                        Db::rollback();
                        return false;
                    }
                }else{
                    Db::rollback();
                    return false;
                }
            }
        }catch (Exception $e){
            Db::rollback();
            return false;
        }
    }


    public function FirstDownlod($uid,$down_integral){
        try{
            Db::startTrans();
            $downlod = [
                'user_id'=>$uid,
                'integral'=>$down_integral,
                'type'=>4,
                'remark'=>'首次下载',
                'createtime'=>time(),
            ];
            $where['id']=array('eq',$uid);
            $userOne=$this->model->where($where)->find();
            $userOne=$userOne->toArray();
            if(empty($userOne['is_first'])){
                $downlod_result = $this->SetIntegralInsert($downlod);
            }else{
                $downlod_result=0;
            }
            if($downlod_result){
                $this->model->where($where)->update(['is_first'=>1]);
            }
            Db::commit();

        }catch (\Exception $e){
            Db::rollback();
            return false;
        }
        return true;
    }

    /**
     * 查询店铺/分红金额/股权
     *
     * @param $user_id
     * @return array
     */
    public function capital($user_id){
       $data=array();
       try{
           //店铺
           $data['shopstatus']=Db::name('litestore_shop')->where(['user_id'=>$user_id])->find();
           //分红金额
           $data['user_but']=Db::name('user_money_log')->where(['money_type'=>4,'user_id'=>$user_id])->sum('money');
           //股权
           $data['user_stokc']=Db::name('user_money_log')->where(['money_type'=>5,'user_id'=>$user_id])->sum('money');
       }catch (\Exception $e){

       }
       return $data;
    }

    /**
     * h5端判断加入代理是否显示申请按钮
     *
     * @param $user_id
     * @return mixed
     */
    public function addagentServer($user_id){

        try{
            $user_shop=Db::name('user')
                ->where(['id'=>$user_id,'server_type'=>array('in',array(1,2,3,5))])
                ->count();

            $user_pr=Db::name('user')
                ->where(['id'=>$user_id,'is_agent'=>1])
                ->count();

            if($user_shop>0){
                $prox_shop=1;
            }else{
                $prox_shop=Db::name('proxylog')
                    ->where(['user_id'=>$user_id,'server_type'=>array('in',array(1,2,3,5)),'status'=>array('in',array('0','1'))])
                    ->count();
            }

            if($user_pr>0){
                $prox_pr=1;
            }else{
                $prox_pr=Db::name('proxylog')
                    ->where(['user_id'=>$user_id,'is_agent'=>1,'status'=>array('in',array('0','1'))])
                    ->count();
            }

            if($prox_shop>0){
                $data['prox']='style="display: none"';
            }else{
                $data['prox']='';
            }

            if($prox_pr>0){
                $data['pro']='style="display: none"';
            }else{
                $data['pro']='';
            }
        }catch (\Exception $e){
            $data['pro']='';
            $data['prox']='';
        }
        return $data;
    }

    /**
     * 商家中心财务统计
     *
     * @param $user_id
     * @param $type
     * @param $date
     * @param $endDate
     * @param $week
     * @param $monthDay
     * @param $year
     * @param $page
     * @return array
     */
    public function financialList($user_id,$type,$date,$endDate,$week,$monthDay,$year,$page){
        $data=array();
        try{
            $where['ml.user_id']=array('eq',$user_id);
            if($type==1){
                $where['ml.money_type']=array('in',array('1','2','3','4','5','10','11','13'));
            }elseif($type==2){
            }elseif ($type==3){
                $where['ml.money_type']=array('in',array('12'));
            }elseif ($type==4){
                $where['ml.money_type']=array('in',array('10'));
            }

            //判断如传递年为空就默认当前年
            if(empty($year)){
                $year=date("Y", time()); //年
            }

            //获取指定周开始时间和结束时间
            if(!empty($week)&&!empty($year)){
                $weekArray=weekday($year,$week);
            }else{
                $weekArray=[];
            }

            //获取指定月份开始时间戳和结束时间戳
            if(!empty($year)&&!empty($monthDay)){
                $monthArray=monthday($year,$monthDay);
            }else{
                $monthArray=[];
            }

            if(!empty($date)&empty($endDate)){
                //查询日期
                $dateime=strtotime($date);
                $where2['createtime']=array('between',array($dateime,($dateime+1*24*60*60-1)));
                $where['ml.createtime']=array('between',array($dateime,($dateime+1*24*60*60-1)));
            }elseif(!empty($date)&!empty($endDate)){
                //查询带有开始时间和结束时间
                $dateime=strtotime($date);
                $endDate=strtotime($endDate);
                $where2['createtime']=array('between',array($dateime,$endDate));
                $where['ml.createtime']=array('between',array($dateime,$endDate));
            }elseif(!empty($weekArray)){
                //查询指定周
                $where2['createtime']=array('between',array($weekArray['start'],$weekArray['end']));
                $where['ml.createtime']=array('between',array($monthArray['start'],$monthArray['end']));
            }elseif(!empty($monthArray)){
                //查询指定月
                $where2['createtime']=array('between',array($monthArray['start'],$monthArray['end']));
                $where['ml.createtime']=array('between',array($monthArray['start'],$monthArray['end']));
            }else{
                if(empty($monthDay)){
                    $monthDay=date('m');
                }
                $monthArray=monthday($year,$monthDay);
                $where2['createtime']=array('between',array($monthArray['start'],$monthArray['end']));
                $where['ml.createtime']=array('between',array($monthArray['start'],$monthArray['end']));

            }

            $usermoney=Db::name('user_money_log')
                ->alias('ml')
                ->join('litestore_shoporder o','ml.shoporder_id=o.shoporder_id','LEFT')
                ->field('ml.*,o.playUser_id')
                ->where($where)
                ->page($page)
                ->order('ml.createtime desc')
                ->limit(10)
                ->select();

            $usermoney_sum=
                Db::name('user_money_log')
                    ->alias('ml')
                    ->join('litestore_shoporder o','ml.shoporder_id=o.shoporder_id','LEFT')
                    ->field('ml.*,o.playUser_id')
                    ->where($where)
                    ->sum('money');
            if($type==2){
                $wherem['user_id']=array('eq',$user_id);
                $wherem1['status']=array('in',array('1','2'));
                $usermoney=Db::name('user_deposit')
                    ->where($wherem)
                    ->where($where2)
                    ->field('*,7 as money_type')
                    ->page($page)
                    ->order('createtime desc')
                    ->limit(10)
                    ->select();

                $user=$this->auth->getUser();
                $usermoney_sum=$user->money;
            }


            $shop_res_point=Db::name('litestore_shop')->where(['user_id'=>$user_id])->find();

            foreach ($usermoney as $key=>$val){
                if($val['createtime']){
                    $usermoney[$key]['createtime']=datetime($val['createtime']);
                }
                $usermoney[$key]['shop_res_point']=$shop_res_point['res_point'];

            }
            $data['data']=$usermoney;
            $data['usermoney_sum']=$usermoney_sum;
        }catch (\Exception $e){

        }
        return $data;

    }

    /**
     * h5端扫描支付注册积分
     *
     * @param $user_id
     * @param $parent_id
     * @param $site
     * @return bool
     */
    public function integralCreate($user_id,$parent_id,$site){
       try{
           Db::startTrans();
           Db::name('user')->where(['id'=>$user_id])->setInc('integral',$site['scan_score']);
           $user_integral1['user_id']=$user_id;
           $user_integral1['integral']=$site['scan_score'];
           $user_integral1['type']=1;
           $user_integral1['createtime']=time();
           $user_integral1['remark']='推荐注册送积分';
           Db::name('user_integral')->insert($user_integral1);

           Db::name('user')->where(['id'=>$parent_id])->setInc('integral',$site['recommended_score']);
           $user_integral2['user_id']=$parent_id;
           $user_integral2['integral']=$site['recommended_score'];
           $user_integral2['type']=3;
           $user_integral2['remark']='推荐送积分';
           $user_integral2['createtime']=time();
           Db::name('user_integral')->insert($user_integral2);
           Db::commit();
           $status=true;
       }catch (\Exception $e){
           Db::rollback();
           $status=false;
       }
       return $status;
    }

    /**
     * h5端注册更新用户地址数据(省/市/区)
     *
     * @param $area
     * @param $user_id
     * @return bool
     */
    public function location_city_create($area,$user_id){
        try{
            Db::startTrans();
            $province=Db::name('area')->where(['name'=>$area['province']])->find();
            $areadata['province']=$province['id'];

            $city=Db::name('area')->where(['name'=>$area['city']])->find();
            $areadata['city']=$city['id'];

            $district=Db::name('area')->where(['name'=>$area['district']])->find();
            $areadata['area']=$district['id'];

            Db::name('user')->where(['id'=>$user_id])->update($areadata);
            Db::commit();
            $status=true;
        }catch (\Exception $e){
            Db::rollback();
            $status=false;
        }
        return $status;
    }

    /**
     * H5端支付成功进行返利润和积分级余额处理函数
     *
     * @param $order_no
     * @return bool
     */
    public function orderPlayCompute($order_no){
        try{

            //引入支付函数
            $orderQuery=new OrderQuery();
            //通过订单order_no查找订单信息,是给支付宝和微信支付留的回调中返回的订单编号
            $order=Db::name('litestore_shoporder')->where(['order_no'=>$order_no])->find();

            //更新支付用户支付使用的余额(自己余额-支付余额=自己现在该拥有的余额)
            Db::name('user')->where(['id'=>$order['playUser_id']])->setDec('money',$order['remainder']);

            //通过订单号来查询商家信息,这里是回调中使用留的
            $shop_new=Db::name('litestore_shop')->where(['id'=>$order['litestore_shop_id']])->find();
            if($shop_new['res_point']>0){
                if($shop_new['res_point']>=100){
                    $money_to=$order['play_price']+$order['remainder']; //当让利大于100%,让利等于（订单实际支付金额+订单支付余额）
                }else{
                    //当让利小于100%,让利等于（订单实际支付金额+订单支付余额）*让利比
                    $money_to=($order['play_price']+$order['remainder'])*($shop_new['res_point']/100);
                }

            }else{
                //当让利比小于或等于0,让利=0
                $money_to=0;
            }
            //定义数组给分润、贡献值、消费返点、货款使用数据
            $orderArry=array(
                'order_id'=>$order['shoporder_id'], //支付订单表id
                'shop_id'=>$order['litestore_shop_id'], //商户id
                'order_no'=>$order_no, //支付订单号
                'money'=>$money_to, //让利款
                'user_id'=>$order['playUser_id'], //支付用户id
                'play_price'=>$order['play_price'], //订单实际支付金额
                'total_price'=>$order['total_price'], //订单总支付金额
                'shop_user_id'=>$order['user_id'], //商家用户id
                'money_new'=>$order['Payment_ph'],//商家返货款
                'remainder'=>$order['remainder'] //订单支付使用余额
            );
            if($shop_new['res_point']>0) {
                $orderQuery->orderDispose($orderArry);//分润
            }
            $orderQuery->HostIntegration($orderArry);//自己消费返积分
            $orderQuery->Integration($orderArry); //消费返积分
            $orderQuery->contribution($orderArry);//贡献值
            $orderQuery->consumption($orderArry); //消费返
            $orderQuery->consumptionOrderPlay($orderArry);//返消费总金额
            if($shop_new['res_point']<100){
                $orderQuery->paragraph($orderArry); //货款
            }
            $status=true;
        }catch (\Exception $e){
            $status=false;
        }
        return $status;
    }

    /**
     * h5端下订单插入数据
     *
     * @param $playUser_id
     * @param $order_no
     * @param $shop_id
     * @param $shop_name
     * @param $to_price
     * @param $preferential
     * @param $price
     * @param $shop_user_id
     * @param $category_id
     * @param $Payment_ph
     * @param $remainder
     * @return bool
     */
    public function inserOrder($playUser_id,$order_no,$shop_id,$shop_name,$to_price,$preferential,$price,$shop_user_id,$category_id,$Payment_ph,$remainder,$order_status=1){
        try{
            //商家订单即将插入的数据
            $data=array(
                'order_no'=>$order_no, //订单
                'litestore_shop_id'=>$shop_id, //商家ID
                'shop_name'=>$shop_name, //商家名称
                'order_status'=>$order_status, //默认给1已支付状态
                'play_price'=>$to_price, //实际支付金额
                'play_time'=>time(),    //支付实际
                'createtime'=>time(),  //创建时间
                'preferential'=>$preferential, //首单优惠
                'remainder'=>$remainder,  //余额
                'total_price'=>$price,  //支付用户输入金额
                'user_id'=>$shop_user_id,  //商家用户id
                'litestore_shopcategory_id'=>$category_id, //商家类别id
                'openId'=>'',
                'playUser_id'=>$playUser_id,  //支付用户id
                'Payment_ph'=>$Payment_ph //商家让利款已经计算过
            );
            Db::startTrans();
            Db::name('litestore_shoporder')->insert($data);//插入订单
            Db::commit();
            $status=true;

        }catch (\Exception $e){
            Db::rollback();
            $status=false;
        }
        return $status;
    }

    /**
     * H5申请提现数据处理
     *
     * @param $bank
     * @param $money
     * @param $user
     * @return mixed
     */
    public function temptedAdd($bank,$money,$user){
       try{
           $data['user_id']=$bank['user_id']; //用户id
           $data['banking_id']=$bank['banking_id']; //银行id
           $data['account']=$bank['account'];//银行账户
           $data['branch']=$bank['branch']; //银行支行
           $data['compellation']=$bank['compellation']; //姓名
           $data['type']=$bank['type']; //提现类型类型:默认1=银行
           $data['mobile']=$bank['mobile'];//手机号
           $data['province']=$bank['province'];//省id
           $data['city']=$bank['city'];//市id
           $data['area']=$bank['area'];//区id
           $data['createtime']=time();//创建时间
           $data['status']=1;//状态:1=审核中,2=已审核,3=审核失败
           $data['money']=$money;//提现金额
           $data['cash_fee']=0;//手续费暂时默认为0
           $wheredp['user_id']=array('eq',$user->id);//当前提现用户id
           $wheredp['status']=array('eq','1');//状态:1=审核中
           //查询提现用户审核中的总金额
           $user_deopist=Db::name('user_deposit')->where($wheredp)->sum('money');
           $dep_cou=0;

           //判断提现审核中提现金额是否大于0
           if($user_deopist>0){
               //计算用户余额减去提现审核中金额和现在输入的提现金额，如果小于等于0那就提示
               $dep_cou=$user['money']-$user_deopist-$money;
           }
           if($dep_cou<=0){
               $data=array('code'=>0,'msg'=>'提现金额已超过了可提现金额');
           }else{
               //开始事务
               Db::startTrans();
               $aft=$money;//输入提现金额
               $datamoney['user_id']=$user->id;//提现用户id
               $datamoney['money']=$aft;//提现金额
               $datamoney['before']=$user['money'];//提现请用变化金额
               $datamoney['after']=$user['money']-$aft;//提现后用户变动基恩
               $datamoney['createtime']=time();//创建时间戳
               $datamoney['money_type']=7;//类型：7为提现
               $moneylog_id=Db::name('user_money_log')->insertGetId($datamoney);//插入用户资金变化id
               $data['moneylog_id']=$moneylog_id;//关联用户资金变化id
               Db::name('user_deposit')->insert($data);//插入提现表中
               //当前用户余额增加提现金额
               Db::name('user')->where(['id'=>$user->id])->setDec('money',$money);
               $data=array('code'=>1,'msg'=>'申请成功');
               //事务提交
               Db::commit();
           }
       }catch (\Exception $e){
           $data=array('code'=>0,'msg'=>'申请失败');
       }
       return $data;
    }

    /**
     * 查询用户银行账户
     *
     * @param $user
     * @return array
     */
    public function getUserBank($user){
        try{
            //用户银行卡信息
            $bank=Db::name('user_bank')
                ->alias('ba')
                ->where(['user_id'=>$user->id])
                ->join('banking b','ba.banking_id=b.id','LEFT')
                ->field('ba.*,b.name')
                ->select();

            //用户银行开户加密处理
            foreach ($bank as $key=>$val){
                $bank[$key]['account']=formatBankCardNo($val['account']);
            }
        }catch (\Exception $e){
            $bank=[];
        }
        return $bank;
    }

    /**
     * H5查询订单列表
     *
     * @param $where
     * @param $page
     * @return array
     */
    public function orderListGet($where,$page){
        try{
            //查询订单信息
            $order=Db::name('litestore_shoporder')
                ->alias('o')
                ->join('litestore_shop s','o.litestore_shop_id=s.id','LEFT')
                ->field('o.*,s.name')
                ->where($where)
                ->page($page)
                ->order('o.createtime desc')
                ->limit(10)
                ->select();

            foreach ($order as $key=>$val){
                //时间戳格式化
                if($val['createtime']){
                    $order[$key]['createtime']=datetime($val['createtime']);
                }
                //判断评价状态
                if(empty($val['comment_status'])){
                    $order[$key]['comment_name']='待评价';
                    $order[$key]['p']='评价';
                    $order[$key]['style']=' ';
                }else{
                    $order[$key]['comment_name']='已评价';
                    $order[$key]['p']='';
                    $order[$key]['style']=' style="display:none"';
                }
                //订单显示金额=订单支付金额+订单余额
                $order[$key]['total']=$val['play_price']+$val['remainder'];
            }
        }catch (\Exception $e){
            $order=[];
        }
        return $order;
    }

    /**
     * 插入提现记录表数据
     *
     * @param $price
     * @param $fullname
     * @param $phone
     * @param $account
     * @param $branch
     * @param $regione
     * @param $user_id
     * @return bool
     */
    public function proxyAdd($price,$fullname,$phone,$account,$branch,$regione,$user_id){
        try{
            Db::startTrans();
            $data['price']=$price;
            $data['fullname']=$fullname;
            $data['phone']=$phone;
            $data['account']=$account;
            $data['branch']=$branch;
            $data['regione']=$regione;
            $data['createtime'] = time();
            $data['user_id'] =$user_id;
            $data['status'] = 0;
            Db::name('proxylog')->insert($data);
            Db::commit();
            $status=true;
        }catch (\Exception $e){
            Db::rollback();
            $status=false;
        }
        return $status;
    }


    /**
     * H5端订单评价操作
     *
     * @param $data
     * @param $litestore_shop_id
     * @param $litestore_shoporder_id
     * @param $user_id
     * @return bool
     */
    public function commentGet($data,$litestore_shop_id,$litestore_shoporder_id,$user_id){
        try{
            $data['litestore_shop_id']=$litestore_shop_id; //商铺id
            $data['litestore_shoporder_id']=$litestore_shoporder_id; //订单id
            $data['puser_id']=$user_id;//用户id
            $data['createtime']=time();//创建时间戳
            $shopComment=new \app\common\model\ShopComment();
            $shopOrder=new \app\common\model\LitestoreShoporder();
            $shop=new \app\common\model\LitestoreShop();
            $shopComment->insert($data);//插入商铺评论表中
            //商铺所有的评分总和
            $average_sum=$shopComment->where(['litestore_shop_id'=>$litestore_shop_id])->sum('psoce');
            //商铺所有评论条数
            $average_count=$shopComment->where(['litestore_shop_id'=>$litestore_shop_id])->count('psoce');
            //计算平均分
            $udata['average']=round ($average_sum/$average_count);
            //评论当前商铺平均评分更新
            $shop->where(['id'=>$litestore_shop_id])->update($udata);
            $ud['comment_status']=1;
            $shopOrder->where(['shoporder_id'=>$litestore_shoporder_id])->update($ud);
            $status=true;
        }catch (\Exception $e){
            $status=false;
        }
        return $status;
    }

    /**
     *提现明细列表
     *
     * @param $where
     * @param $page
     * @return array
     */
    public function accountdetailGet($where,$page){
        try{
            $depositModel=new \app\common\model\UserDeposit();
            $data=$depositModel
                ->where($where)
                ->page($page)
                ->order('createtime desc')
                ->limit(10)
                ->select();

            foreach ($data as $key=>$val){
                if($val['createtime']){
                    $usermoney[$key]['createtime']=datetime($val['createtime']);
                }
            }
        }catch (\Exception $e){
            $data=[];
        }
        return $data;
    }



}